package ibm.abacus.classpath;

import ibm.abacus.javaagent.PnpCore;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.JarFile;

/**
 * It introduced two ways to add jar file to system class loader.
 * 
 * @author huchangchun
 */

public class AddJarToSystem {

	public static void main(String[] args) throws IOException {
		instrumentWay();

		contextWay();

		System.out.println("Done!");
	}

	/**
	 * The class in Abacus.jar can be loaded by setting context class loader.
	 * 
	 * @throws MalformedURLException
	 */
	private static void contextWay() throws MalformedURLException {
		File f = new File("C:\\Abacus.jar");
		URL url = f.toURI().toURL();
		URLClassLoader cl = URLClassLoader.newInstance(new URL[] { url });
		Thread.currentThread().setContextClassLoader(cl);

		try {
			Class.forName("ibm.abacus.classpath.Abacus");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * The class in ibm.jar can be loaded by appending the jar file to system
	 * class loader.
	 * Steps of using instrument
	 * 1. Archive the PnpCore class. In this example, archive PnpCore.class into start.jar
	 * 2. Modify MANIFEST.MF file. Appending Premain-Class and other options if needed.
	 * 3. Set Java option -javaagent=start.jar to run Java
	 * 
	 * @throws IOException
	 */
	private static void instrumentWay() throws IOException {
		JarFile jarfile = new JarFile(
				"D:\\workspace\\eclipse\\ibm.abacus.quote\\bin\\ibm.jar");
		PnpCore.instrument.appendToSystemClassLoaderSearch(jarfile);

		try {
			Class.forName("ibm.abacus.quote.Trd");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
